package com.atguigu.day1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//ReentrantLock()独占锁，synchronized也是独占锁
//ReentrantLock默认是非公平+独占锁
public class SyncVSLockDemo {
    //synchronized无退出机制，一个线程调用该方法，后续线程只能同步等待
    public synchronized void m1() {
        System.out.println(Thread.currentThread().getName() + "\t" + "------come in");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    //新建一个Lock锁
    private Lock lock = new ReentrantLock();

    //Lock锁,试探锁方法,抢不到直接退出
    public void m2() {
        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "------come in");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "\t" + "抢锁失败，下次再来");
        }
    }

    //加等待时间的Lock锁，在等待时间内抢不到直接退出
    public void m3() {
        try {
            if (lock.tryLock(3,TimeUnit.SECONDS)) {
                try {
                    System.out.println(Thread.currentThread().getName() + "\t" + "------come in");
                    try {
                        TimeUnit.SECONDS.sleep(4);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "\t" + "抢锁失败，下次再来");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        SyncVSLockDemo syncVSLockDemo = new SyncVSLockDemo();
        new Thread(() -> {
            syncVSLockDemo.m2();
        }, "A").start();
        new Thread(() -> {
            syncVSLockDemo.m2();
        }, "B").start();
    }
}
